package com.greenline.pay.biz.manager.common;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public abstract class AbstractLocalCache <K extends Object,T extends Object>{

	    private final  Map<Object, Object> data =new HashMap<Object, Object>();

	    private final ReadWriteLock lock = new ReentrantReadWriteLock();


	    private long updateTime = 0L;

	    // 更新间隔10分钟
	    private  long updateInterval = 10 * 60 * 1000000000L;
	    
	    
	    protected long getUpdateInterval() {
			return updateInterval;
		}

	    protected void setUpdateInterval(long updateInterval) {
			this.updateInterval = updateInterval;
		}
	  
	    
	   public abstract K getkey(T t);
	   
	   public abstract List<T> listData();

	    @SuppressWarnings("unchecked")
		public T get(K k) {
	    	long nona = System.nanoTime();
	        if (nona - updateTime > updateInterval) {
	            reload();
	        }
	        lock.readLock().lock();
	        T t = null;
	        try {
	            t = (T)data.get(k);
	        } finally {
	            lock.readLock().unlock();
	        }
	        return t;
	    }

	    public void reload() {
	        lock.writeLock().lock();
	        try {
	            List<T> list = listData();
	            data.clear();
	            if (list != null) {
	                for (T t : list) {
	                    data.put(getkey(t), t);
	                }
	            }
	        } finally {
	            updateTime = System.nanoTime();
	            lock.writeLock().unlock();
	        }
	    }

}
